package com.qwe.graduation.controller.core;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qwe.graduation.entity.User;
import com.qwe.graduation.domain.dto.UserDto;
import com.qwe.graduation.service.IUserService;
import com.qwe.graduation.shiro.utils.JwtUtil;
import com.qwe.graduation.utils.RedisUtil;
import com.qwe.graduation.utils.Result;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author lzf
 * @date 2022/11/7 14:16
 * @description UserLoginController
 */

@RestController
@RequestMapping("/user")
@CrossOrigin //跨域？
@Slf4j
public class UserLoginController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private IUserService IUserService;

    /**
     * 登录用户
     */
    @ApiOperation(value = "登录用户", notes = "登录用户")
    @GetMapping("/login")
    public Result login(@RequestParam(required = false) String username,
                        @RequestParam(required = false) String password,
                        @RequestParam(required = false) String code,
                        @RequestParam(required = false) String codeId){
//        ValidatorUtils.validateEntity(user, ValidGroups.AddGroup.class);
        if (!check(codeId, code)){
            return Result.error("验证码错误");
        }
        User user = IUserService.getOne(new LambdaQueryWrapper<User>().eq(User::getName, username));
        if(user == null){
            return Result.error("用户不存在");
        }
        if (!user.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        String token = JwtUtil.sign(user.getId(), user.getPassword());
        return Result.OK("登录成功",token);
    }

    /**
     * 注册用户
     */
    @ApiOperation(value = "注册用户", notes = "注册用户")
    @GetMapping("/save")
    public Result save(@RequestBody UserDto userDto){
//        String token = JwtUtil.sign(user.getId(), user.getPassword());
        User user = IUserService.getOne(new LambdaQueryWrapper<User>().eq(User::getName, userDto.getName()));
        if (user != null){
            Result.error("用户名已经注册，请重新输入");
        }
        user.setId(UUID.randomUUID().toString());
        IUserService.save(user);
        return Result.OK("注册成功");
    }


    /**
     * 校验图形验证码
     * @param
     * @return
     */
    @PostMapping(value = "/check")
    public boolean check(String id,String code) {
//        JSONObject jsonObject = JSON.parseObject(info);
//        获取传过来的id 和 code
//        String id = jsonObject.getString("id");
//        String code = jsonObject.getString("code");
        String s = "";
        //获取redis里面存的code
        Object obj = redisUtil.get(id);
        if(obj != null){
            s = obj.toString();
        }
        //比较输入的code和redis的code
        boolean flag = code.equalsIgnoreCase(s);
        //匹配成功就删除redis存储
        if(flag){
            redisUtil.del(id);
            System.out.println("验证码成功");
        }
        return flag;
    }

    /**
     * 图形验证码
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/captcha")
    public String captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setFont(Captcha.FONT_1);
        String id = UUID.randomUUID().toString();
        response.setHeader("id", id);
        CaptchaUtil.out(specCaptcha, request, response);
        String verCode = specCaptcha.text().toLowerCase();
        //不设置过期
        //redisUtil.set(id, verCode);
        //设置一分钟过期
        redisUtil.set(id,verCode,8000);
        System.out.println(id);
        return id;
    }
}
